// app/routes/users.tsx
import React, { useEffect, useState } from 'react';  // 导入 useState 和 useEffect
import { LoaderFunction, json, LinksFunction, MetaFunction } from '@remix-run/node';
import { useAsyncError, useFetcher } from '@remix-run/react';
import { searchUsers, searchUsersGoodRate, searchUsersTask } from 'server/services/userService';
import dayjs from 'dayjs';
import stylesUrl from "../../styles/user_serch.css";
import { getUserOrderSummary, getPaidTaskDown, getSummary, getSharePointCount, getChannelAll } from '~/api/large';
// import { getSettingConfig } from '~/api/setting';

// 关键的代码是这部分，把 links export 出去
export const links: LinksFunction = () => {
  return [{ rel: "stylesheet", href: stylesUrl }];
};

export const meta: MetaFunction = () => {
  return [
    { title: "large screen" },
    { name: "description", content: "Welcome to large screen!" },
    { name: "viewport", content: "width=device-width, initial-scale=1" },
  ];
};

export const loader: LoaderFunction = async () => {
  // try {
  //   console.log(orderItem.data)
  //   // const { aigcTaskCount } = await searchUsersTask();
  //   return json({ ...orderItem.data });
  // } catch (error) {
  //   console.error(error);
  //   return json({ error: true });
  // }
  return {};
};

// React 组件展示用户数量
export function Users() {
  const [seconds, setSeconds] = useState(getNextFridayCountdown());
  const [orderUserTotal, setUserNum] = useState('0.00');
  const [orderTotal, setOrderTotal] = useState('0.00');
  const [payUserTotal, setPayUserTotal] = useState('0.00');
  const [payOrderTotal, setPayOrderTotal] = useState('0.00');
  const [paidTaskList, setPaidTaskList] = useState([]);
  const [showTime, setShowTime] = useState(dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss"));
  // const [shareObj, setShareObj] = useState({ share: 0, newUser: 0 });
  const [fissionData, setFissionData] = useState<any>({});
  // const error = useAsyncError();

  useEffect(() => {
    let interval;
    let taskRateInterval;
    const loadData = async () => {
      try {
        // const { data:summary } = await getSummary();
        const { data:channelAllData } = await getChannelAll();
        //  if (summary && summary?.questSummarys) {
        //     const freeItem = (summary?.questSummarys || []).filter(item => item.Template == "second_free")[0]
        //     if (freeItem) {
        //       setShareComplateCount(freeItem.CompletedUserNum)
        //     }
        //   }
        const { data } = await getUserOrderSummary();
        if (data && data.servedUserNum) {
          setUserNum(data.servedUserNum);
        }
        if (channelAllData) {
          setFissionData(channelAllData)
          setOrderTotal(channelAllData.orderTotal || 0);
        }
        if (channelAllData) {
          setPayUserTotal(channelAllData.payUserTotal || 0);
        }
        if (channelAllData) {
          setPayOrderTotal(channelAllData.payOrderTotal || 0);
        }
        // await getSettingItem();
        // 在这里处理响应的数据
      } catch (e) {
        console.error("请求/large_screen时出现错误", e);
        // 在这里处理异常
      }
    };

    interval = setInterval(() => {
      loadData();
    }, 1000 * 60 * 2);

    const getPaidData = async () => {
      const { data } = await getPaidTaskDown();
        if (data?.summaries && data?.summaries.length) {
          setPaidTaskList(data?.summaries)
        }
    }

    // const getSettingItem = async () => {
    //   try {
    //     const { data } = await getSharePointCount()
    //     setShareObj({ share: data.saveUserShareTotal, newUser: data.scanNewUserTotal });
    //   } catch(e) {
    //     console.log(e);
    //   }
    // }

    taskRateInterval = setInterval(() => {
      getPaidData();
    }, 1000 * 60 * 30);

    const dataInIt = async () => {
      await loadData();
      await getPaidData();
    }

    dataInIt();

    return () => {
      clearInterval(interval);
    };
  }, []);

  useEffect(() => {
      const interval1 = setInterval(() => {
          setSeconds(getNextFridayCountdown());
      }, 1000);

      const interval2 = setInterval(() => {
          setShowTime(dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss:SSS") + Math.floor((Math.random() * 900000 + 100000)));
      }, 79);

      return () => {
        clearInterval(interval1)
        clearInterval(interval2)
      };
  }, []);

  const totalFissionUsers = (fissionData?.sharePullNewLinkCount || 0) + (fissionData?.sharePhotoPullNewUserCount || 0) || 0;
  const totalFissionOrders = (fissionData?.shareOrderLinkCount || 0) + (fissionData?.sharePhotoOrderCount || 0) || 0;
  const totalFissionPaidOrders = (fissionData?.sharePayOrderLinkCount || 0) + (fissionData?.sharePhotoPayOrderCount || 0) || 0;
  const fissionCoef = totalFissionUsers / ((Number(orderUserTotal) - totalFissionUsers) || 1);

  return (
    <div className='user_server_page'>
      <h1>漫咔叽线上已服务用户: {orderUserTotal}，订单：{orderTotal}，平均下单： {Number(orderUserTotal || 0) > 0 ? (Number(orderTotal || 0) / Number(orderUserTotal || 0)).toFixed(2) : 0}</h1>
      <h1>漫咔叽线上已付费用户: {payUserTotal}，订单：{payOrderTotal}，平均下单： {Number(payUserTotal) > 0 ? (Number(payOrderTotal || 0) / Number(payUserTotal || 0)).toFixed(2) : 0}</h1>
      {/* <h1>完成分享免单：{shareComplateCount}</h1> */}
      <h3>分享图片保存：{fissionData?.sharePhotoSaveCount}次，成功拉新：{fissionData?.sharePhotoPullNewUserCount || 0}人</h3>
      {/* 裂变系数新增 */}
      <h3>发出分享链接：{fissionData?.shareSendLinkCount || 0}次，成功拉新：{fissionData?.sharePullNewLinkCount || 0}人，成功下单：{ fissionData?.shareOrderLinkCount || 0}，付费订单：{ fissionData?.sharePayOrderLinkCount || 0}</h3>
      <h3>保存分享图片：{fissionData?.sharePhotoSaveCount || 0}次，成功拉新：{fissionData?.sharePhotoPullNewUserCount || 0}人，成功下单：{ fissionData?.sharePhotoOrderCount || 0}，付费订单：{ fissionData?.sharePhotoPayOrderCount || 0}</h3>
      <h3>总裂变人数：{totalFissionUsers || 0}，总裂变订单：{totalFissionOrders || 0}，总裂变付费订单：{totalFissionPaidOrders || 0}</h3>
      {/* <h3>裂变系数：{fissionCoef.toFixed(2) || 0}</h3> */}
      <h3>裂变系数：{fissionCoef.toFixed(2) || 0}</h3>
      <span style={{textAlign: 'left'}}>
        {getPaidDom(paidTaskList)}
      </span>
      <h2>距离疯狂星期五倒计时: {formatCountdown(seconds)} </h2>
      <span className='time'>{showTime}</span>
    </div>
  );
}

function getNextFridayCountdown(): number {
  const now = new Date();
  const nextFriday = new Date();

  // 设置下一个周五的日期和时间
  nextFriday.setDate(now.getDate() + (5 - now.getDay() + 7) % 7);
  nextFriday.setHours(10, 0, 0, 0); // 设为早上10点

  // 如果已经是周五且时间超过10点，则计算下一个周五
  if (now.getDay() === 5 && now.getTime() > nextFriday.getTime()) {
      nextFriday.setDate(nextFriday.getDate() + 7);
  }

  // 计算倒计时（秒）
  const secondsUntilNextFriday = Math.round((nextFriday.getTime() - now.getTime()) / 1000);

  return secondsUntilNextFriday;
}

function formatCountdown(seconds) {
  const days = Math.floor(seconds / (3600*24));
  const hours = Math.floor(seconds % (3600*24) / 3600);
  const minutes = Math.floor(seconds % 3600 / 60);
  const secs = Math.floor(seconds % 60);

  return `${days > 0 ? days + '天' : ''}${hours > 0 ? hours + '小时' : ''}${minutes > 0 ? minutes + '分钟' : ''}${secs > 0 ? secs + '秒' : ''}`.trim();
}

export default function UsersWithErrorBoundary() {
  return (
      <Users />
  );
}

const getPaidDom = (paidTaskList) => {
  return (
    (paidTaskList || []).map((item) => {
      let startStr;
      let  gender;
      let startRate;
      let bodyRate;
      if (item.timeWindowDays == 7) {
        startStr = "（7 天）";
      } else if (item.paid) {
        startStr = "（付费）";
      } else {
        startStr = "（全部）";
      }
      if (item.gender == 'woman') {
        gender = "女生";
      } else {
        gender = "男生";
      }
      if (item.rate) {
        startRate = ((item.rate || 0) * 100).toFixed(2);
      }
      bodyRate = item.taskFavorites.map(item => `下载≥${item.favoriteImageNumThreshold}：${((item.taskRate || 0)*100).toFixed(2)}%`)
      return (
        <h3>{startStr}{gender}{bodyRate}</h3>
      )
    })
  )
}